<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.4.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"wan-lei8.gitee.io","root":"/","scheme":"Pisces","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":false,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}}};
  </script>

  <meta name="description" content="为什么要用异步框架，它解决什么问题？">
<meta property="og:type" content="article">
<meta property="og:title" content="SpringBoot异步编排">
<meta property="og:url" content="https://wan-lei8.gitee.io/2020/09/05/SpringBoot%E5%BC%82%E6%AD%A5%E7%BC%96%E6%8E%92/index.html">
<meta property="og:site_name" content="程序员西桐">
<meta property="og:description" content="为什么要用异步框架，它解决什么问题？">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2020-09-05T01:50:20.000Z">
<meta property="article:modified_time" content="2021-12-22T02:41:58.432Z">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="https://wan-lei8.gitee.io/2020/09/05/SpringBoot%E5%BC%82%E6%AD%A5%E7%BC%96%E6%8E%92/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>SpringBoot异步编排 | 程序员西桐</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">程序员西桐</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">但行好事，莫问前程</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a>

  </li>
  </ul>
</nav>




</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://wan-lei8.gitee.io/2020/09/05/SpringBoot%E5%BC%82%E6%AD%A5%E7%BC%96%E6%8E%92/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.png">
      <meta itemprop="name" content="">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="程序员西桐">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          SpringBoot异步编排
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2020-09-05 09:50:20" itemprop="dateCreated datePublished" datetime="2020-09-05T09:50:20+08:00">2020-09-05</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2021-12-22 10:41:58" itemprop="dateModified" datetime="2021-12-22T10:41:58+08:00">2021-12-22</time>
              </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h3 id="为什么要用异步框架，它解决什么问题？"><a href="#为什么要用异步框架，它解决什么问题？" class="headerlink" title="为什么要用异步框架，它解决什么问题？"></a>为什么要用异步框架，它解决什么问题？</h3><span id="more"></span>

<p>在SpringBoot的日常开发中，一般都是同步调用的。但实际中有很多场景非常适合使用异步来处理，如：注册新用户，送100个积分；或下单成功，发送push消息等等。</p>
<p>就拿注册新用户这个用例来说，为什么要异步处理？</p>
<ul>
<li>第一个原因：容错性、健壮性，如果送积分出现异常，不能因为送积分而导致用户注册失败；因为用户注册是主要功能，送积分是次要功能，即使送积分异常也要提示用户注册成功，然后后面在针对积分异常做补偿处理。</li>
<li>第二个原因：提升性能，例如注册用户花了20毫秒，送积分花费50毫秒，如果用同步的话，总耗时70毫秒，用异步的话，无需等待积分，故耗时20毫秒。</li>
</ul>
<p>故，异步能解决2个问题，性能和容错性。</p>
<h4 id="SpringBoot如何实现异步调用？"><a href="#SpringBoot如何实现异步调用？" class="headerlink" title="SpringBoot如何实现异步调用？"></a>SpringBoot如何实现异步调用？</h4><p>对于异步方法调用，从Spring3开始提供了<code>@Async</code>注解，我们只需要在方法上标注此注解，此方法即可实现异步调用。</p>
<p>当然，我们还需要一个配置类，通过Enable模块驱动注解<code>@EnableAsync</code> 来开启异步功能。</p>
<h4 id="实现异步调用"><a href="#实现异步调用" class="headerlink" title="实现异步调用"></a>实现异步调用</h4><ol>
<li><p><strong>新建配置类，开启@Async功能支持</strong></p>
<p>使用<code>@EnableAsync</code>来开启异步任务支持，<code>@EnableAsync</code>注解可以直接放在SpringBoot启动类上，也可以单独放在其他配置类上。我们这里选择使用单独的配置类<code>SyncConfiguration</code>。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="meta">@EnableAsync</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">AsyncConfiguration</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></li>
<li><p><strong>在方法上标记异步调用</strong></p>
<p>增加一个Component类，用来进行业务处理，同时添加<code>@Async</code>注解，代表该方法为异步处理。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Component</span></span><br><span class="line"><span class="meta">@Slf4j</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">AsyncTask</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@SneakyThrows</span></span><br><span class="line">    <span class="meta">@Async</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">doTask1</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">long</span> t1 = System.currentTimeMillis();</span><br><span class="line">        Thread.sleep(<span class="number">2000</span>);</span><br><span class="line">        <span class="keyword">long</span> t2 = System.currentTimeMillis();</span><br><span class="line">        log.info(<span class="string">&quot;task1 cost &#123;&#125; ms&quot;</span> , t2-t1);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@SneakyThrows</span></span><br><span class="line">    <span class="meta">@Async</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">doTask2</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">long</span> t1 = System.currentTimeMillis();</span><br><span class="line">        Thread.sleep(<span class="number">3000</span>);</span><br><span class="line">        <span class="keyword">long</span> t2 = System.currentTimeMillis();</span><br><span class="line">        log.info(<span class="string">&quot;task2 cost &#123;&#125; ms&quot;</span> , t2-t1);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></li>
<li><p><strong>在Controller中进行异步调用</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@RestController</span></span><br><span class="line"><span class="meta">@RequestMapping(&quot;/async&quot;)</span></span><br><span class="line"><span class="meta">@Slf4j</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">AsyncController</span> </span>&#123;</span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> AsyncTask asyncTask;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@RequestMapping(&quot;/task&quot;)</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">task</span><span class="params">()</span> <span class="keyword">throws</span> InterruptedException </span>&#123;</span><br><span class="line">        <span class="keyword">long</span> t1 = System.currentTimeMillis();</span><br><span class="line">        asyncTask.doTask1();</span><br><span class="line">        asyncTask.doTask2();</span><br><span class="line">        Thread.sleep(<span class="number">1000</span>);</span><br><span class="line">        <span class="keyword">long</span> t2 = System.currentTimeMillis();</span><br><span class="line">        log.info(<span class="string">&quot;main cost &#123;&#125; ms&quot;</span>, t2-t1);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>通过访问<code>http://localhost:8080/async/task</code>查看控制台日志：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">2021</span>-<span class="number">11</span>-<span class="number">25</span> <span class="number">15</span>:<span class="number">48</span>:<span class="number">37</span> [http-nio-<span class="number">8080</span>-exec-<span class="number">8</span>] INFO  com.jianzh5.blog.async.AsyncController:<span class="number">26</span> - main cost <span class="number">1009</span> ms</span><br><span class="line"><span class="number">2021</span>-<span class="number">11</span>-<span class="number">25</span> <span class="number">15</span>:<span class="number">48</span>:<span class="number">38</span> [task-<span class="number">1</span>] INFO  com.jianzh5.blog.async.AsyncTask:<span class="number">22</span> - task1 cost <span class="number">2005</span> ms</span><br><span class="line"><span class="number">2021</span>-<span class="number">11</span>-<span class="number">25</span> <span class="number">15</span>:<span class="number">48</span>:<span class="number">39</span> [task-<span class="number">2</span>] INFO  com.jianzh5.blog.async.AsyncTask:<span class="number">31</span> - task2 cost <span class="number">3005</span> ms</span><br></pre></td></tr></table></figure>

<p>通过日志可以看到：主线程不需要等待异步方法执行完成，减少了响应时间，提高了接口性能。</p>
<h3 id="注意-上面的代码忽略了一个最大的问题，就是给-Async异步框架自定义线程池。"><a href="#注意-上面的代码忽略了一个最大的问题，就是给-Async异步框架自定义线程池。" class="headerlink" title="注意:上面的代码忽略了一个最大的问题，就是给@Async异步框架自定义线程池。"></a>注意:<strong>上面的代码忽略了一个最大的问题，就是给<code>@Async</code>异步框架自定义线程池</strong>。</h3></li>
</ol>
<h4 id="为什么要给-Async自定义线程池？"><a href="#为什么要给-Async自定义线程池？" class="headerlink" title="为什么要给@Async自定义线程池？"></a>为什么要给@Async自定义线程池？</h4><p>​    使用<code>@Async</code>注解，在默认情况下用的是<strong>SimpleAsyncTaskExecutor线程池，该线程池不是真正意义上的线程池</strong>。</p>
<p>​    使用此线程池无法实现线程重用，每次调用都会新建一条线程。若系统中不断的创建线程，最终会导致系统占用内存过高，引发<code>OutOfMemoryError</code>错误，关键    代码如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">execute</span><span class="params">(Runnable task, <span class="keyword">long</span> startTimeout)</span> </span>&#123;</span><br><span class="line">  Assert.notNull(task, <span class="string">&quot;Runnable must not be null&quot;</span>);</span><br><span class="line">  Runnable taskToUse = <span class="keyword">this</span>.taskDecorator != <span class="keyword">null</span> ? <span class="keyword">this</span>.taskDecorator.decorate(task) : task;</span><br><span class="line">  <span class="comment">//判断是否开启限流，默认为否</span></span><br><span class="line">  <span class="keyword">if</span> (<span class="keyword">this</span>.isThrottleActive() &amp;&amp; startTimeout &gt; <span class="number">0L</span>) &#123;</span><br><span class="line">    <span class="comment">//执行前置操作，进行限流</span></span><br><span class="line">    <span class="keyword">this</span>.concurrencyThrottle.beforeAccess();</span><br><span class="line">    <span class="keyword">this</span>.doExecute(<span class="keyword">new</span> SimpleAsyncTaskExecutor.ConcurrencyThrottlingRunnable(taskToUse));</span><br><span class="line">  &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    <span class="comment">//未限流的情况，执行线程任务</span></span><br><span class="line">    <span class="keyword">this</span>.doExecute(taskToUse);</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">doExecute</span><span class="params">(Runnable task)</span> </span>&#123;</span><br><span class="line">  <span class="comment">//不断创建线程</span></span><br><span class="line">  Thread thread = <span class="keyword">this</span>.threadFactory != <span class="keyword">null</span> ? <span class="keyword">this</span>.threadFactory.newThread(task) : <span class="keyword">this</span>.createThread(task);</span><br><span class="line">  thread.start();</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//创建线程</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> Thread <span class="title">createThread</span><span class="params">(Runnable runnable)</span> </span>&#123;</span><br><span class="line">  <span class="comment">//指定线程名，task-1，task-2...</span></span><br><span class="line">  Thread thread = <span class="keyword">new</span> Thread(<span class="keyword">this</span>.getThreadGroup(), runnable, <span class="keyword">this</span>.nextThreadName());</span><br><span class="line">  thread.setPriority(<span class="keyword">this</span>.getThreadPriority());</span><br><span class="line">  thread.setDaemon(<span class="keyword">this</span>.isDaemon());</span><br><span class="line">  <span class="keyword">return</span> thread;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>我们也可以直接通过上面的控制台日志观察，每次打印的线程名都是[task-1]、[task-2]、[task-3]、[task-4]…..递增的。</p>
<p>正因如此，所以我们在使用Spring中的@Async异步框架时一定要自定义线程池，替代默认的<code>SimpleAsyncTaskExecutor</code>。</p>
<p><strong>Spring提供了多种线程池：</strong></p>
<ul>
<li><code>SimpleAsyncTaskExecutor</code>：不是真的线程池，这个类不重用线程，每次调用都会创建一个新的线程。</li>
<li><code>SyncTaskExecutor</code>：这个类没有实现异步调用，只是一个同步操作。只适用于不需要多线程的地方</li>
<li><code>ConcurrentTaskExecutor</code>：Executor的适配类，不推荐使用。如果ThreadPoolTaskExecutor不满足要求时，才用考虑使用这个类</li>
<li><code>ThreadPoolTaskScheduler</code>：可以使用cron表达式</li>
<li><code>ThreadPoolTaskExecutor</code> ：最常使用，推荐。其实质是对java.util.concurrent.ThreadPoolExecutor的包装</li>
</ul>
<p><strong>为@Async实现一个自定义线程池</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="meta">@EnableAsync</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">SyncConfiguration</span> </span>&#123;</span><br><span class="line">    <span class="meta">@Bean(name = &quot;asyncPoolTaskExecutor&quot;)</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> ThreadPoolTaskExecutor <span class="title">executor</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        ThreadPoolTaskExecutor taskExecutor = <span class="keyword">new</span> ThreadPoolTaskExecutor();</span><br><span class="line">        <span class="comment">//核心线程数</span></span><br><span class="line">        taskExecutor.setCorePoolSize(<span class="number">10</span>);</span><br><span class="line">        <span class="comment">//线程池维护线程的最大数量,只有在缓冲队列满了之后才会申请超过核心线程数的线程</span></span><br><span class="line">        taskExecutor.setMaxPoolSize(<span class="number">100</span>);</span><br><span class="line">        <span class="comment">//缓存队列</span></span><br><span class="line">        taskExecutor.setQueueCapacity(<span class="number">50</span>);</span><br><span class="line">        <span class="comment">//许的空闲时间,当超过了核心线程出之外的线程在空闲时间到达之后会被销毁</span></span><br><span class="line">        taskExecutor.setKeepAliveSeconds(<span class="number">200</span>);</span><br><span class="line">        <span class="comment">//异步方法内部线程名称</span></span><br><span class="line">        taskExecutor.setThreadNamePrefix(<span class="string">&quot;async-&quot;</span>);</span><br><span class="line">        <span class="comment">/**</span></span><br><span class="line"><span class="comment">         * 当线程池的任务缓存队列已满并且线程池中的线程数目达到maximumPoolSize，如果还有任务到来就会采取任务拒绝策略</span></span><br><span class="line"><span class="comment">         * 通常有以下四种策略：</span></span><br><span class="line"><span class="comment">         * ThreadPoolExecutor.AbortPolicy:丢弃任务并抛出RejectedExecutionException异常。</span></span><br><span class="line"><span class="comment">         * ThreadPoolExecutor.DiscardPolicy：也是丢弃任务，但是不抛出异常。</span></span><br><span class="line"><span class="comment">         * ThreadPoolExecutor.DiscardOldestPolicy：丢弃队列最前面的任务，然后重新尝试执行任务（重复此过程）</span></span><br><span class="line"><span class="comment">         * ThreadPoolExecutor.CallerRunsPolicy：重试添加当前的任务，自动重复调用 execute() 方法，直到成功</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        taskExecutor.setRejectedExecutionHandler(<span class="keyword">new</span> ThreadPoolExecutor.CallerRunsPolicy());</span><br><span class="line">        taskExecutor.initialize();</span><br><span class="line">        <span class="keyword">return</span> taskExecutor;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>配置自定义线程池以后我们就可以大胆的使用<code>@Async</code>提供的异步处理能力了。</p>
<p><strong>多个线程处理</strong></p>
<p>在现实的互联网项目开发中，针对高并发的请求，一般的做法是高并发接口单独线程池隔离处理。</p>
<p>假设现在2个高并发接口：一个是修改用户信息接口，刷新用户redis缓存；一个是下订单接口，发送app push信息。往往会根据接口特征定义两个线程池，这时候我们在使用<code>@Async</code>时就需要通过指定线程池名称进行区分。</p>
<p><strong>为Async指定线程名称</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@SneakyThrows</span></span><br><span class="line"><span class="meta">@Async(&quot;asyncPoolTaskExecutor&quot;)</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">doTask1</span><span class="params">()</span> </span>&#123;</span><br><span class="line">  <span class="keyword">long</span> t1 = System.currentTimeMillis();</span><br><span class="line">  Thread.sleep(<span class="number">2000</span>);</span><br><span class="line">  <span class="keyword">long</span> t2 = System.currentTimeMillis();</span><br><span class="line">  log.info(<span class="string">&quot;task1 cost &#123;&#125; ms&quot;</span> , t2-t1);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>当系统存在多个线程池时，我们也可以配置一个默认线程池，对于非默认的异步任务再通过<code>@Async(&quot;otherTaskExecutor&quot;)</code>来指定线程池名称。</p>
<p><strong>配置默认线程池</strong></p>
<p>可以修改配置类让其实现<code>AsyncConfigurer</code>，并重写<code>getAsyncExecutor()</code>方法，指定默认线程池：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="meta">@EnableAsync</span></span><br><span class="line"><span class="meta">@Slf4j</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">AsyncConfiguration</span> <span class="keyword">implements</span> <span class="title">AsyncConfigurer</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Bean(name = &quot;asyncPoolTaskExecutor&quot;)</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> ThreadPoolTaskExecutor <span class="title">executor</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        ThreadPoolTaskExecutor taskExecutor = <span class="keyword">new</span> ThreadPoolTaskExecutor();</span><br><span class="line">        <span class="comment">//核心线程数</span></span><br><span class="line">        taskExecutor.setCorePoolSize(<span class="number">2</span>);</span><br><span class="line">        <span class="comment">//线程池维护线程的最大数量,只有在缓冲队列满了之后才会申请超过核心线程数的线程</span></span><br><span class="line">        taskExecutor.setMaxPoolSize(<span class="number">10</span>);</span><br><span class="line">        <span class="comment">//缓存队列</span></span><br><span class="line">        taskExecutor.setQueueCapacity(<span class="number">50</span>);</span><br><span class="line">        <span class="comment">//许的空闲时间,当超过了核心线程出之外的线程在空闲时间到达之后会被销毁</span></span><br><span class="line">        taskExecutor.setKeepAliveSeconds(<span class="number">200</span>);</span><br><span class="line">        <span class="comment">//异步方法内部线程名称</span></span><br><span class="line">        taskExecutor.setThreadNamePrefix(<span class="string">&quot;async-&quot;</span>);</span><br><span class="line">        <span class="comment">/**</span></span><br><span class="line"><span class="comment">         * 当线程池的任务缓存队列已满并且线程池中的线程数目达到maximumPoolSize，如果还有任务到来就会采取任务拒绝策略</span></span><br><span class="line"><span class="comment">         * 通常有以下四种策略：</span></span><br><span class="line"><span class="comment">         * ThreadPoolExecutor.AbortPolicy:丢弃任务并抛出RejectedExecutionException异常。</span></span><br><span class="line"><span class="comment">         * ThreadPoolExecutor.DiscardPolicy：也是丢弃任务，但是不抛出异常。</span></span><br><span class="line"><span class="comment">         * ThreadPoolExecutor.DiscardOldestPolicy：丢弃队列最前面的任务，然后重新尝试执行任务（重复此过程）</span></span><br><span class="line"><span class="comment">         * ThreadPoolExecutor.CallerRunsPolicy：重试添加当前的任务，自动重复调用 execute() 方法，直到成功</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        taskExecutor.setRejectedExecutionHandler(<span class="keyword">new</span> ThreadPoolExecutor.CallerRunsPolicy());</span><br><span class="line">        taskExecutor.initialize();</span><br><span class="line">        <span class="keyword">return</span> taskExecutor;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 指定默认线程池</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Executor <span class="title">getAsyncExecutor</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> executor();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> AsyncUncaughtExceptionHandler <span class="title">getAsyncUncaughtExceptionHandler</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> (ex, method, params) -&gt;</span><br><span class="line">            log.error(<span class="string">&quot;线程池执行任务发送未知错误,执行方法：&#123;&#125;&quot;</span>,method.getName(),ex);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>如下，<code>doTask1()</code>方法使用默认使用线程池<code>asyncPoolTaskExecutor</code>，<code>doTask2()</code>使用线程池<code>otherTaskExecutor</code>，非常灵活。</p>

    </div>
<div>
  
    <div>
    
        <div style="text-align:center;color: #ccc;font-size:14px;">-------------本文结束<i class="fa fa-paw"></i>感谢您的阅读-------------</div>
    
</div>

  
</div>

    
    
    
        

<div>
<ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者： </strong>
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="https://wan-lei8.gitee.io/2020/09/05/SpringBoot%E5%BC%82%E6%AD%A5%E7%BC%96%E6%8E%92/" title="SpringBoot异步编排">https://wan-lei8.gitee.io/2020/09/05/SpringBoot异步编排/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh" rel="noopener" target="_blank"><i class="fab fa-fw fa-creative-commons"></i>BY-NC-SA</a> 许可协议。转载请注明出处！
  </li>
</ul>
</div>


      <footer class="post-footer">

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2020/08/21/%E4%B8%BA%E4%BB%80%E4%B9%88IDEA%E4%B8%8D%E6%8E%A8%E8%8D%90%E4%BD%A0%E4%BD%BF%E7%94%A8-Autowired/" rel="prev" title="为什么IDEA不推荐你使用@Autowired?">
      <i class="fa fa-chevron-left"></i> 为什么IDEA不推荐你使用@Autowired?
    </a></div>
      <div class="post-nav-item">
    <a href="/2020/10/12/MVC%E4%B8%89%E5%B1%82%E6%9E%B6%E6%9E%84%E5%8A%A0Manager%E5%B1%82/" rel="next" title="MVC三层架构加Manager层">
      MVC三层架构加Manager层 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E4%B8%BA%E4%BB%80%E4%B9%88%E8%A6%81%E7%94%A8%E5%BC%82%E6%AD%A5%E6%A1%86%E6%9E%B6%EF%BC%8C%E5%AE%83%E8%A7%A3%E5%86%B3%E4%BB%80%E4%B9%88%E9%97%AE%E9%A2%98%EF%BC%9F"><span class="nav-number">1.</span> <span class="nav-text">为什么要用异步框架，它解决什么问题？</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#SpringBoot%E5%A6%82%E4%BD%95%E5%AE%9E%E7%8E%B0%E5%BC%82%E6%AD%A5%E8%B0%83%E7%94%A8%EF%BC%9F"><span class="nav-number">1.1.</span> <span class="nav-text">SpringBoot如何实现异步调用？</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E5%AE%9E%E7%8E%B0%E5%BC%82%E6%AD%A5%E8%B0%83%E7%94%A8"><span class="nav-number">1.2.</span> <span class="nav-text">实现异步调用</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%B3%A8%E6%84%8F-%E4%B8%8A%E9%9D%A2%E7%9A%84%E4%BB%A3%E7%A0%81%E5%BF%BD%E7%95%A5%E4%BA%86%E4%B8%80%E4%B8%AA%E6%9C%80%E5%A4%A7%E7%9A%84%E9%97%AE%E9%A2%98%EF%BC%8C%E5%B0%B1%E6%98%AF%E7%BB%99-Async%E5%BC%82%E6%AD%A5%E6%A1%86%E6%9E%B6%E8%87%AA%E5%AE%9A%E4%B9%89%E7%BA%BF%E7%A8%8B%E6%B1%A0%E3%80%82"><span class="nav-number">2.</span> <span class="nav-text">注意:上面的代码忽略了一个最大的问题，就是给@Async异步框架自定义线程池。</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#%E4%B8%BA%E4%BB%80%E4%B9%88%E8%A6%81%E7%BB%99-Async%E8%87%AA%E5%AE%9A%E4%B9%89%E7%BA%BF%E7%A8%8B%E6%B1%A0%EF%BC%9F"><span class="nav-number">2.1.</span> <span class="nav-text">为什么要给@Async自定义线程池？</span></a></li></ol></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt=""
      src="/images/avatar.png">
  <p class="site-author-name" itemprop="name"></p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives">
          <span class="site-state-item-count">41</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/yourname" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;yourname" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="/malegod958@163.com" title="E-Mail → malegod958@163.com"><i class="fa fa-envelope fa-fw"></i>E-Mail</a>
      </span>
  </div>
  <div class="cc-license motion-element" itemprop="license">
    <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh" class="cc-opacity" rel="noopener" target="_blank"><img src="/images/cc-by-nc-sa.svg" alt="Creative Commons"></a>
  </div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 2018 – 
  <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">万磊</span>
</div>
  <div class="powered-by">

  </div>

        








      </div>
    </footer>
  </div>

  
  
  <script color='' opacity='0.5' zIndex='-1' count='99' src="/lib/canvas-nest/canvas-nest.min.js"></script>
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>




  















  

  

  
	<script type="text/javascript" src="//cdn.bootcss.com/canvas-nest.js/1.0.0/canvas-nest.min.js"></script>
	

<script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"log":false,"pluginJsPath":"lib/","pluginModelPath":"assets/","pluginRootPath":"live2dw/","tagMode":false});</script></body>
</html>
<!-- 页面点击小红心 -->
<script type="text/javascript" src="/js/src/clicklove.js"></script>
